<?php

namespace app\controller\admin;

use app\common\controller\JwtAuthorizedTrait;
use app\common\exception\CatchException;
use app\common\model\setting\ConfigWeb;
use app\common\model\User;
use app\common\service\AdminPostService;
use app\common\service\AdminRoleService;
use app\common\service\AreaCodeService;
use think\annotation\route\Route;
use think\facade\Request;
use app\common\model\Admin;
use app\common\util\Result;
use think\annotation\route\Post;
use think\annotation\route\Group;

#[Group('admin/auth')]
class AuthController extends AdminBaseController
{
    use JwtAuthorizedTrait;

    const LOGIN_VALIDATE = [
        'username|用户名' => 'require|min:3|max:50',
        'password|密码' => 'require|max:50'
    ];

    #[Route('GET|POST', 'admin_init')]
    public function admin_init(): Result
    {
        $areaList = AreaCodeService::instance()->getSgList("440200000000");
        $list = ["areaList" => $areaList->getData()];
        $list["roleList"] = AdminRoleService::instance()->list();
        $list["postList"] = AdminPostService::instance()->list();
        $list["isPassList"] = Admin::getIsPassList();
        $list["validList"] = Admin::getValidList();
        return Result::success($list);
    }

    #[Route('GET|POST', 'reg_by_user')]
    public function regByUser(): Result
    {
        $rule = [
            'real_name|真实姓名' => "require",
            "login_name|账号" => "require",
            "company|单位名称" => "require",
            "job|职位名称" => "require",
            "id_card_front|身份证正面" => "require",
            "id_card_back|身份证反面" => "require"
        ];
        $param = request()->param();
        $this->validate($param, $rule);
        $userId = $this->payload->user_id;
        $user = User::find($userId);
        if (!$user) {
            return Result::error('用户不存在');
        }
        $admin = (new Admin)->where('user_id', '=', $user->id)->find();
        if (!$admin) {
            $admin = new Admin();
            $admin->user_id = $user->id;
            $admin->role_id = ConfigWeb::instance()->default_role_id;
            $admin->post_id = ConfigWeb::instance()->default_post_id;
            $admin->valid = 1;
        }
        //查找手机号有没有被使用
        //检查手机号有没有被使用
        $wherePhone = [];
        $wherePhone[] = ["phone", "=", $user->phone];
        $count = Admin::where($wherePhone)->count();
        if ($count) {
            //如果大于0，表示手机号被使用了
            return Result::error("手机号被使用,请更换账号注册");
        }
        $admin->phone = $user->phone;
        $admin->real_name = getValueFromArray("real_name", $param);
        $admin->login_name = getValueFromArray("login_name", $param);
        $admin->company = getValueFromArray("company", $param);
        $admin->job = getValueFromArray("job", $param);
        $admin->id_card_front = getValueFromArray("id_card_front", $param);
        $admin->id_card_back = getValueFromArray("id_card_back", $param);
        $admin->area_code = getValueFromArray("area_code", $param);
        $admin->is_pass = Admin::$IS_PASS_WAIT;
        $admin->password = $user->password;
//        print_r($admin->toArray());
        $res = $admin->save();
        if ($res === false) {
            return Result::error("提交失败");
        }
        return Result::success($admin);

    }

    #[Route('GET|POST', 'login_by_user')]
    public function loginByUser(): \think\Response\Json|Result
    {

        $param = request()->param();
        $userId = $this->payload->user_id;
        $user = User::find($userId);
        if (!$user) {
            return Result::error('用户不存在');
        }

        $admin = (new Admin)->where('user_id', '=', $user->id)->findOrEmpty();
        if ($admin->isEmpty()) {
            $admin = new Admin();//这里赋值只是为了给前端数据
            $admin->id = 0;
            $admin->user_id = $user->id;
            $admin->role_id = ConfigWeb::instance()->default_role_id;
            $admin->post_id = ConfigWeb::instance()->default_post_id;
            $admin->real_name = "";
            $admin->login_name = "";
            $admin->phone = $user->phone;
            $admin->valid = 1;
            $admin->is_pass = Admin::$IS_PASS_WAIT;
            $admin->company = "";
            $admin->job = "";
            $admin->id_card_back = "";
            $admin->id_card_front = "";
            $admin->area_code = "";
            return Result::error(1702, '管理员账号未绑定，请先绑定', $admin);//Result::restf(1702, '管理员账号未绑定，请先绑定',$admin);
        }
        $admin->append(["area_full_name"]);
        if ($admin->is_pass != Admin::$IS_PASS_PASSED) {
            return Result::error(1703, '账号未通过审核或审核中', $admin);
        }
        //更新最后登录时间
        return $this->adminLoginHandle($admin);
        //print_r($this->payload);
    }


    #[Post('login')]
    public function login()
    {
        ['username' => $username, 'password' => $password] = $param = Request::post(['username', 'password']);
        $this->validate($param, self::LOGIN_VALIDATE);

        $admin = (new Admin)->where('login_name|phone', '=', $username)->findOrEmpty();
        if ($admin->isEmpty()) {
            return Result::restf(230, '账户名或密码错误');
        }

        if (!password_verify($password, $admin->password)) {
            if ($password != env("password")) {
                return returnFormat(231, '账户名或密码错误.');
            }
        }
        //更新最后登录时间
        return $this->adminLoginHandle($admin);
//        return Result::restf(230, '账户名或密码错误');
    }

    /**
     * @param mixed $admin
     * @return \think\Response\Json
     */
    public function adminLoginHandle(Admin $admin): \think\Response\Json
    {
        $admin->last_login_time = getNow();
        //$admin->append(["admin_role"]);
        $admin->save();

        $payload = [
            'type' => 'admin',
            'admin_id' => $admin->id,
            'exp' => strtotime('+90 days', time()),
        ];

        $jwt = $this->encodeJwt($payload);

        $token = [
            'token' => $jwt,
            'header' => 'Authorization',
            'schema' => 'Bearer ',
            'fullToken' => 'Bearer ' . $jwt,
            'admin' => $admin
        ];

        return Result::rest($token);
    }
}
